const fs = require('fs');
const path = require('path');

function findLatestRun() {
  const artifactsDir = 'diagnostics-artifacts';
  if (!fs.existsSync(artifactsDir)) {
    console.error('No diagnostics artifacts found');
    process.exit(1);
  }
  
  const runs = fs.readdirSync(artifactsDir)
    .filter(name => name.startsWith('run-'))
    .sort((a, b) => {
      const timeA = parseInt(a.replace('run-', ''));
      const timeB = parseInt(b.replace('run-', ''));
      return timeB - timeA;
    });
  
  if (runs.length === 0) {
    console.error('No test runs found');
    process.exit(1);
  }
  
  return path.join(artifactsDir, runs[0]);
}

function loadPageData(runDir, pageName) {
  const pageDir = path.join(runDir, 'pages', pageName);
  if (!fs.existsSync(pageDir)) {
    return null;
  }
  
  const data = {};
  
  try {
    if (fs.existsSync(path.join(pageDir, 'console.json'))) {
      data.console = JSON.parse(fs.readFileSync(path.join(pageDir, 'console.json'), 'utf8'));
    }
    
    if (fs.existsSync(path.join(pageDir, 'network.json'))) {
      data.network = JSON.parse(fs.readFileSync(path.join(pageDir, 'network.json'), 'utf8'));
    }
    
    if (fs.existsSync(path.join(pageDir, 'metrics.json'))) {
      data.metrics = JSON.parse(fs.readFileSync(path.join(pageDir, 'metrics.json'), 'utf8'));
    }
    
    if (fs.existsSync(path.join(pageDir, 'errors.json'))) {
      data.errors = JSON.parse(fs.readFileSync(path.join(pageDir, 'errors.json'), 'utf8'));
    }
    
    data.hasScreenshot = fs.existsSync(path.join(pageDir, 'screenshot.png'));
    data.hasErrorScreenshot = fs.existsSync(path.join(pageDir, 'error-screenshot.png'));
  } catch (error) {
    console.warn(`Error loading data for ${pageName}:`, error.message);
  }
  
  return data;
}

function generateSummary() {
  const runDir = findLatestRun();
  const runId = path.basename(runDir);
  const timestamp = new Date(parseInt(runId.replace('run-', ''))).toISOString();
  
  console.log(`Generating summary for run: ${runId}`);
  
  const pages = ['dashboard', 'orders', 'coupons', 'social_review', 'invites'];
  const summary = {
    runId,
    timestamp,
    pages: {},
    totals: {
      blocker: 0,
      major: 0,
      minor: 0,
      whiteScreens: 0,
      apiErrors: 0,
      imageErrors: 0,
      totalRequests: 0,
      failedRequests: 0
    },
    details: {
      blockerErrors: [],
      majorErrors: [],
      apiEndpointStatus: {},
      placeholderImageUrls: [],
      domainResolutionErrors: []
    }
  };
  
  for (const pageName of pages) {
    const pageData = loadPageData(runDir, pageName);
    if (!pageData) {
      console.warn(`No data found for page: ${pageName}`);
      continue;
    }
    
    const pageRoute = pageName === 'social_review' ? '/social-review' : `/${pageName}`;
    
    summary.pages[pageRoute] = {
      hasContent: pageData.metrics?.hasContent || false,
      loadTime: pageData.metrics?.loadTime || 0,
      resourceCount: pageData.metrics?.resourceCount || 0,
      errorCount: pageData.metrics?.errorCount || 0,
      warningCount: pageData.metrics?.warningCount || 0,
      hasScreenshot: pageData.hasScreenshot,
      hasErrorScreenshot: pageData.hasErrorScreenshot
    };
    
    // 统计错误
    if (pageData.errors) {
      summary.totals.blocker += pageData.errors.blocker?.length || 0;
      summary.totals.major += pageData.errors.major?.length || 0;
      summary.totals.minor += pageData.errors.minor?.length || 0;
      
      if (pageData.errors.blocker) {
        summary.details.blockerErrors.push(...pageData.errors.blocker.map(e => ({
          ...e,
          page: pageRoute
        })));
      }
      
      if (pageData.errors.major) {
        summary.details.majorErrors.push(...pageData.errors.major.map(e => ({
          ...e,
          page: pageRoute
        })));
      }
    }
    
    // 统计白屏
    if (!pageData.metrics?.hasContent) {
      summary.totals.whiteScreens++;
    }
    
    // 统计网络请求
    if (pageData.network) {
      summary.totals.totalRequests += pageData.network.length;
      
      for (const req of pageData.network) {
        // API错误统计
        if (req.url.includes('/api/')) {
          const endpoint = req.url.replace(/^.*\/api/, '/api').split('?')[0];
          if (!summary.details.apiEndpointStatus[endpoint]) {
            summary.details.apiEndpointStatus[endpoint] = { success: 0, error: 0, total: 0 };
          }
          summary.details.apiEndpointStatus[endpoint].total++;
          
          if (req.failed || (req.status && req.status >= 400)) {
            summary.details.apiEndpointStatus[endpoint].error++;
            summary.totals.apiErrors++;
          } else {
            summary.details.apiEndpointStatus[endpoint].success++;
          }
        }
        
        // 占位图片统计 - 只检测外部占位符服务
        if ((req.url.includes('placeholder.com') || req.url.includes('via.placeholder')) && !req.url.startsWith('/images/')) {
          summary.details.placeholderImageUrls.push({
            url: req.url,
            page: pageRoute,
            status: req.status,
            failed: req.failed
          });
          
          if (req.failed || (req.status && req.status >= 400)) {
            summary.totals.imageErrors++;
          }
        }
        
        // 域名解析错误
        if (req.failed && req.failure && req.failure.errorText && 
            req.failure.errorText.includes('ERR_NAME_NOT_RESOLVED')) {
          summary.details.domainResolutionErrors.push({
            url: req.url,
            page: pageRoute,
            error: req.failure.errorText
          });
        }
        
        if (req.failed || (req.status && req.status >= 400)) {
          summary.totals.failedRequests++;
        }
      }
    }
  }
  
  // 保存JSON报告
  fs.writeFileSync(path.join(runDir, 'summary.json'), JSON.stringify(summary, null, 2));
  
  // 生成HTML报告
  generateHtmlReport(runDir, summary);
  
  // 输出结果
  console.log('\n=== DIAGNOSTICS SUMMARY ===');
  console.log(`Run ID: ${summary.runId}`);
  console.log(`Timestamp: ${summary.timestamp}`);
  console.log(`\nError Counts:`);
  console.log(`  Blocker: ${summary.totals.blocker}`);
  console.log(`  Major: ${summary.totals.major}`);
  console.log(`  Minor: ${summary.totals.minor}`);
  console.log(`\nPage Status:`);
  console.log(`  White Screens: ${summary.totals.whiteScreens}`);
  console.log(`  API Errors: ${summary.totals.apiErrors}`);
  console.log(`  Image Errors: ${summary.totals.imageErrors}`);
  console.log(`\nNetwork:`);
  console.log(`  Total Requests: ${summary.totals.totalRequests}`);
  console.log(`  Failed Requests: ${summary.totals.failedRequests}`);
  
  if (summary.details.placeholderImageUrls.length > 0) {
    console.log(`\nPlaceholder Images Found: ${summary.details.placeholderImageUrls.length}`);
    summary.details.placeholderImageUrls.forEach(img => {
      console.log(`  - ${img.url} (${img.page}) - Status: ${img.status || 'Failed'}`);
    });
  }
  
  if (summary.details.domainResolutionErrors.length > 0) {
    console.log(`\nDomain Resolution Errors: ${summary.details.domainResolutionErrors.length}`);
    summary.details.domainResolutionErrors.forEach(err => {
      console.log(`  - ${err.url} (${err.page}) - ${err.error}`);
    });
  }
  
  // CI失败判定
  const shouldFail = summary.totals.blocker > 0 || summary.totals.major > 0;
  if (shouldFail) {
    console.log('\n❌ CI FAILURE: Blocker or Major errors detected');
    process.exit(1);
  } else {
    console.log('\n✅ CI SUCCESS: No blocking or major errors');
    process.exit(0);
  }
}

function generateHtmlReport(runDir, summary) {
  const html = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Diagnostics Report - ${summary.runId}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { border-bottom: 2px solid #eee; padding-bottom: 20px; margin-bottom: 20px; }
        .status { display: inline-block; padding: 4px 12px; border-radius: 4px; color: white; font-weight: bold; }
        .status.success { background: #28a745; }
        .status.warning { background: #ffc107; color: #000; }
        .status.error { background: #dc3545; }
        .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin: 20px 0; }
        .card { border: 1px solid #ddd; border-radius: 8px; padding: 15px; background: white; }
        .card h3 { margin-top: 0; color: #333; }
        .metric { display: flex; justify-content: space-between; margin: 8px 0; }
        .error-list { max-height: 200px; overflow-y: auto; }
        .error-item { background: #f8f9fa; border-left: 4px solid #dc3545; padding: 8px; margin: 4px 0; font-size: 12px; }
        .error-item.warning { border-left-color: #ffc107; }
        .screenshot { max-width: 100%; border: 1px solid #ddd; border-radius: 4px; }
        .api-table { width: 100%; border-collapse: collapse; margin: 10px 0; }
        .api-table th, .api-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        .api-table th { background: #f8f9fa; }
        .url-list { max-height: 150px; overflow-y: auto; font-size: 12px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Browser Diagnostics Report</h1>
            <p><strong>Run ID:</strong> ${summary.runId}</p>
            <p><strong>Timestamp:</strong> ${summary.timestamp}</p>
            <p><strong>Status:</strong> 
                <span class="status ${summary.totals.blocker > 0 ? 'error' : summary.totals.major > 0 ? 'warning' : 'success'}">
                    ${summary.totals.blocker > 0 ? 'FAILED' : summary.totals.major > 0 ? 'WARNING' : 'PASSED'}
                </span>
            </p>
        </div>
        
        <div class="grid">
            <div class="card">
                <h3>Error Summary</h3>
                <div class="metric"><span>Blocker Errors:</span><span class="status ${summary.totals.blocker > 0 ? 'error' : 'success'}">${summary.totals.blocker}</span></div>
                <div class="metric"><span>Major Errors:</span><span class="status ${summary.totals.major > 0 ? 'warning' : 'success'}">${summary.totals.major}</span></div>
                <div class="metric"><span>Minor Issues:</span><span>${summary.totals.minor}</span></div>
                <div class="metric"><span>White Screens:</span><span class="status ${summary.totals.whiteScreens > 0 ? 'error' : 'success'}">${summary.totals.whiteScreens}</span></div>
            </div>
            
            <div class="card">
                <h3>Network Summary</h3>
                <div class="metric"><span>Total Requests:</span><span>${summary.totals.totalRequests}</span></div>
                <div class="metric"><span>Failed Requests:</span><span class="status ${summary.totals.failedRequests > 0 ? 'warning' : 'success'}">${summary.totals.failedRequests}</span></div>
                <div class="metric"><span>API Errors:</span><span class="status ${summary.totals.apiErrors > 0 ? 'error' : 'success'}">${summary.totals.apiErrors}</span></div>
                <div class="metric"><span>Image Errors:</span><span class="status ${summary.totals.imageErrors > 0 ? 'warning' : 'success'}">${summary.totals.imageErrors}</span></div>
            </div>
        </div>
        
        <div class="card">
            <h3>Page Status</h3>
            <table class="api-table">
                <thead>
                    <tr><th>Page</th><th>Content</th><th>Load Time</th><th>Resources</th><th>Errors</th><th>Warnings</th><th>Screenshot</th></tr>
                </thead>
                <tbody>
                    ${Object.entries(summary.pages).map(([page, data]) => `
                        <tr>
                            <td>${page}</td>
                            <td><span class="status ${data.hasContent ? 'success' : 'error'}">${data.hasContent ? 'OK' : 'FAIL'}</span></td>
                            <td>${data.loadTime}ms</td>
                            <td>${data.resourceCount}</td>
                            <td class="status ${data.errorCount > 0 ? 'error' : 'success'}">${data.errorCount}</td>
                            <td class="status ${data.warningCount > 0 ? 'warning' : 'success'}">${data.warningCount}</td>
                            <td>${data.hasScreenshot ? '<a href="./pages/' + page.replace('/', '').replace('-', '_') + '/screenshot.png">View</a>' : 'N/A'}</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
        
        ${summary.details.blockerErrors.length > 0 ? `
        <div class="card">
            <h3>Blocker Errors</h3>
            <div class="error-list">
                ${summary.details.blockerErrors.map(err => `
                    <div class="error-item">
                        <strong>${err.page}:</strong> ${err.text}
                        ${err.location ? `<br><small>Location: ${err.location.url}:${err.location.lineNumber}:${err.location.columnNumber}</small>` : ''}
                    </div>
                `).join('')}
            </div>
        </div>
        ` : ''}
        
        ${summary.details.majorErrors.length > 0 ? `
        <div class="card">
            <h3>Major Errors</h3>
            <div class="error-list">
                ${summary.details.majorErrors.map(err => `
                    <div class="error-item warning">
                        <strong>${err.page}:</strong> ${err.text}
                        ${err.location ? `<br><small>Location: ${err.location.url}:${err.location.lineNumber}:${err.location.columnNumber}</small>` : ''}
                    </div>
                `).join('')}
            </div>
        </div>
        ` : ''}
        
        <div class="card">
            <h3>API Endpoint Status</h3>
            <table class="api-table">
                <thead>
                    <tr><th>Endpoint</th><th>Total</th><th>Success</th><th>Error</th><th>Success Rate</th></tr>
                </thead>
                <tbody>
                    ${Object.entries(summary.details.apiEndpointStatus).map(([endpoint, stats]) => {
                        const successRate = stats.total > 0 ? ((stats.success / stats.total) * 100).toFixed(1) : '0';
                        return `
                            <tr>
                                <td>${endpoint}</td>
                                <td>${stats.total}</td>
                                <td class="status success">${stats.success}</td>
                                <td class="status ${stats.error > 0 ? 'error' : 'success'}">${stats.error}</td>
                                <td class="status ${parseFloat(successRate) < 100 ? 'warning' : 'success'}">${successRate}%</td>
                            </tr>
                        `;
                    }).join('')}
                </tbody>
            </table>
        </div>
        
        ${summary.details.placeholderImageUrls.length > 0 ? `
        <div class="card">
            <h3>Placeholder Images (${summary.details.placeholderImageUrls.length})</h3>
            <div class="url-list">
                ${summary.details.placeholderImageUrls.map(img => `
                    <div><strong>${img.page}:</strong> ${img.url} - Status: ${img.status || 'Failed'}</div>
                `).join('')}
            </div>
        </div>
        ` : ''}
        
        ${summary.details.domainResolutionErrors.length > 0 ? `
        <div class="card">
            <h3>Domain Resolution Errors (${summary.details.domainResolutionErrors.length})</h3>
            <div class="url-list">
                ${summary.details.domainResolutionErrors.map(err => `
                    <div><strong>${err.page}:</strong> ${err.url} - ${err.error}</div>
                `).join('')}
            </div>
        </div>
        ` : ''}
        
        <div class="card">
            <h3>Generated Files</h3>
            <ul>
                <li><a href="./summary.json">summary.json</a> - Machine-readable summary</li>
                ${Object.keys(summary.pages).map(page => {
                    const pageName = page.replace('/', '').replace('-', '_') || 'root';
                    return `
                        <li><strong>${page}:</strong>
                            <a href="./pages/${pageName}/console.json">console.json</a> |
                            <a href="./pages/${pageName}/network.json">network.json</a> |
                            <a href="./pages/${pageName}/metrics.json">metrics.json</a> |
                            <a href="./pages/${pageName}/errors.json">errors.json</a>
                            ${summary.pages[page].hasScreenshot ? ` | <a href="./pages/${pageName}/screenshot.png">screenshot.png</a>` : ''}
                        </li>
                    `;
                }).join('')}
            </ul>
        </div>
    </div>
</body>
</html>
  `;
  
  fs.writeFileSync(path.join(runDir, 'summary.html'), html);
  console.log(`HTML report generated: ${path.join(runDir, 'summary.html')}`);
}

if (require.main === module) {
  generateSummary();
}

module.exports = { generateSummary };